startInit()
//注册自定义消息
function registerMessage(type,propertys){
    var messageName = type; // 消息名称。
    var objectName = "s:" + type; // 消息内置名称，请按照此格式命名 *:* 。
    var mesasgeTag = new RongIMLib.MessageTag(true,true); //true true 保存且计数，false false 不保存不计数。
    RongIMClient.registerMessageType(messageName, objectName, mesasgeTag, propertys);
}
function startInit(user,targetId){
    var params = {
        appKey : getValue("appKey"),
        token : getValue("token")
        // navi : getValue("navi")
    };
    console.log(params)
    var userId = "";
    var callbacks = {
        getInstance : function(instance){
            RongIMLib.RongIMEmoji.init();
            //instance.sendMessage
            //注册 PersonMessage
            var propertys = ["name","age","gender"]; // 消息类中的属性名。
            registerMessage("PersonMessage",propertys);
            //注册 ProductMessage
            var propertys = ["price","title","desc","images"]; // 消息类中的属性名。
            registerMessage("ProductMessage",propertys);
        },
        getCurrentUser : function(userInfo){
            console.log(userInfo.userId);
            userId = userInfo.userId;
            console.log("链接成功；userid=" + userInfo.userId);
            document.titie = ("链接成功；userid=" + userInfo.userId);
            //加入聊天室
            //joinChatRoom();
            //发送消息
            sendMessage();
            //获取单群聊历史消息
            //singleChatInfo()
        },
        receiveNewMessage : function(message){
            //判断是否有 @ 自己的消息
            var mentionedInfo = message.content.mentionedInfo || {};
            var ids = mentionedInfo.userIdList || [];
            for(var i=0; i < ids.length; i++){
                if( ids[i] == userId){
                    console.log("有人 @ 了你！");
                }
            }
            showResult("show1",message);
            messageOutput(message);
        }
    };
    initrongyun(params,callbacks);
}
function getValue(id){
    console.log(id)
    return document.getElementById(id).value;
}
function joinChatRoom(){
    var chatRoomId = getValue("chatRoomId");
    // chatRoomId = chatRoomId.replace(/(^\s*)|(\s*$)/g, " ");
    if(chatRoomId == ""){
        console.log("请输入聊天室 id！");
        return false;
    }
    var IM = RongIMClient.getInstance();
    IM.joinChatRoom(chatRoomId, 50, {
        onSuccess: function() {
            console.log("加入聊天室 " + chatRoomId + " 成功");
        },
        onError: function(error) {
            console.log("加入聊天室失败");
        }
    });
}
function initrongyun(params, callbacks, modules){
    var appKey = params.appKey;
    var token = params.token;
    var navi = params.navi || "";

    modules = modules || {};
    var RongIMLib = modules.RongIMLib || window.RongIMLib;
    var RongIMClient = RongIMLib.RongIMClient;
    var protobuf = modules.protobuf || null;
    var config = {};
    //私有云切换navi导航，私有云格式 '120.92.10.214:8888'
    if(navi !== ""){
        config.navi = navi;
    }
    //私有云切换api,私有云格式 '172.20.210.38:81:8888'
    var api = params.api || "";
    if(api !== ""){
        config.api = api;
    }
    //support protobuf url + function
    if(protobuf != null){
        config.protobuf = protobuf;
    }
    var dataProvider = null;
    var imClient = params.imClient;
    if (imClient) {
        dataProvider = new RongIMLib.VCDataProvider(imClient);
    }
    RongIMLib.RongIMClient.init(appKey, dataProvider, config);
    var instance = RongIMClient.getInstance();
    // 连接状态监听器
    RongIMClient.setConnectionStatusListener({
        onChanged: function (status) {
            // console.log(status);
            switch (status) {
                case RongIMLib.ConnectionStatus["CONNECTED"]:
                case 0:
                    console.log("连接成功");
                    callbacks.getInstance && callbacks.getInstance(instance);
                    break;

                case RongIMLib.ConnectionStatus["CONNECTING"]:
                case 1:
                    console.log("连接中");
                    break;

                case RongIMLib.ConnectionStatus["DISCONNECTED"]:
                case 2:
                    console.log("当前用户主动断开链接");
                    break;

                case RongIMLib.ConnectionStatus["NETWORK_UNAVAILABLE"]:
                case 3:
                    console.log("网络不可用");
                    break;

                case RongIMLib.ConnectionStatus["CONNECTION_CLOSED"]:
                case 4:
                    console.log("未知原因，连接关闭");
                    break;

                case RongIMLib.ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"]:
                case 6:
                    console.log("用户账户在其他设备登录，本机会被踢掉线");
                    break;

                case RongIMLib.ConnectionStatus["DOMAIN_INCORRECT"]:
                case 12:
                    console.log("当前运行域名错误，请检查安全域名配置");
                    break;
            }
        }
    });
    /*
    文档：http://www.rongcloud.cn/docs/web.html#3、设置消息监听器
    注意事项：
        1：为了看到接收效果，需要另外一个用户向本用户发消息
        2：判断会话唯一性 ：conversationType + targetId
        3：显示消息在页面前，需要判断是否属于当前会话，避免消息错乱。
        4：消息体属性说明可参考：http://rongcloud.cn/docs/api/js/index.html
    */
    RongIMClient.setOnReceiveMessageListener({
        // 接收到的消息
        onReceived: function (message) {
            // 判断消息类型
            console.log("新消息: " + message.targetId);
            console.log(message);
            callbacks.receiveNewMessage && callbacks.receiveNewMessage(message);
        }
    });
    //开始链接
    RongIMClient.connect(token, {
        onSuccess: function(userId) {
            callbacks.getCurrentUser && callbacks.getCurrentUser({userId:userId});
            console.log("链接成功，用户id：" + userId);
        },
        onTokenIncorrect: function() {
            console.log('token无效');
        },
        onError:function(errorCode){
            var info = '';
            switch (errorCode) {
                case RongIMLib.ErrorCode.TIMEOUT:
                    info = '超时';
                    break;
                case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                    info = '未知错误';
                    break;
                case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                    info = '不可接受的协议版本';
                    break;
                case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                    info = 'appkey不正确';
                    break;
                case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                    info = '服务器不可用';
                    break;
            }
            console.log(errorCode);
        }
    }, '');
    var callback = {
        onSuccess: function(userId) {
            console.log("Reconnect successfully." + userId);
        },
        onTokenIncorrect: function() {
            console.log('token无效');
        },
        onError:function(errorCode){
            console.log(errorcode);
        }
    };
    var configs = {
        // 默认 false, true 启用自动重连，启用则为必选参数
        auto: true,
        // 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒，可选
        url: 'cdn.ronghub.com/RongIMLib-2.2.6.min.js',
        // 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选
        rate: [100, 1000, 3000, 6000, 10000]
    };
    RongIMClient.reconnect(callback, configs);
}
//发送文本消息
function sendMessage(){
    var msg = new RongIMLib.TextMessage({content:"h5测试测试测试",extra:"附加信息"});
    var conversationtype = RongIMLib.ConversationType.PRIVATE; // 单聊,其他会话选择相应的消息类型即可。
    var targetId =getValue("circleId"); // 目标 Id
    console.log("targetId="+targetId);
    RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
            onSuccess: function (message) {
                //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                console.log(message)
                console.log("Send successfully");
            },
            onError: function (errorCode,message) {
                var info = '';
                switch (errorCode) {
                    case RongIMLib.ErrorCode.TIMEOUT:
                        info = '超时';
                        break;
                    case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                        info = '未知错误';
                        break;
                    case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                        info = '在黑名单中，无法向对方发送消息';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                        info = '不在讨论组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_GROUP:
                        info = '不在群组中';
                        break;
                    case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                        info = '不在聊天室中';
                        break;
                    default :
                        info = x;
                        break;
                }
                console.log('发送失败:' + info);
            }
        }
    );
}
//获取单群聊历史消息
function singleChatInfo(){
    var conversationType = RongIMLib.ConversationType.PRIVATE; //单聊,其他会话选择相应的消息类型即可。
    var targetId = "1"; // 想获取自己和谁的历史消息，targetId 赋值为对方的 Id。
    var timestrap = 0; // 默认传 null，若从头开始获取历史消息，请赋值为 0 ,timestrap = 0;
    var count = 20; // 每次获取的历史消息条数，范围 0-20 条，可以多次获取。
    RongIMLib.RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, timestrap, count, {
        onSuccess: function(list, hasMsg) {
            // list => Message 数组。
            // hasMsg => 是否还有历史消息可以获取。
            console.log(list)
        },
        onError: function(error) {
            console.log("GetHistoryMessages,errorcode:" + error);
        }
    });
}